package com.xzx.helloworld;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

/**
 *
 * @author xinzhixuan
 * @version 1.0
 * @date 2025/10/14 18:02
 */
public class TimerServerHandler extends ChannelInboundHandlerAdapter {

    /**
     * 当连接准备就绪，即将开始接收数据时调用
     * 让我们在这个方法中写一个32位整数来表示当前时间
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("channelActive");
        ByteBuf time = ctx.alloc().buffer(4);
        time.writeInt((int) (System.currentTimeMillis() / 1000L + 2208988800L));

        ChannelFuture future = ctx.writeAndFlush(time);
        future.addListener(new ChannelFutureListener() {

            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                System.out.println("Write data to client");
                // 测试，发完数据关闭了连接
                // ctx.close();
            }
        });

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("exceptionCaught");
        cause.printStackTrace();
        ctx.close();
    }
}
